/*************************************************************
 * File: StringHelper.java
 * Copyright (c) 2012
 * Author: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Jan 15, 2013
 * Description: 
 ************************************************************/
package snow.core.toolkit;

import java.util.Date;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

/**
 *
 */
public class StringHelper {

	private static final Random RANDOM = new Random();

	public static String getLineTimeStamp() {
		return DateHelper.format(new Date(), "yyyyMMddHHmmssSSS");
	}

	public static String format(byte byteval) {
		return format(Integer.toHexString(byteval), 2);
	}

	public static String format(short shortval) {
		return format(Integer.toHexString(shortval), 4);
	}

	public static String format(int intval) {
		return format(Integer.toHexString(intval), 8);
	}

	public static String format(long longval) {
		return format(Long.toHexString(longval), 16);
	}

	public static String format(String formatted, int length) {
		return format(formatted, length, '0');
	}

	/**
	 * 字符串格式化
	 * 
	 * @param formatted
	 *            需要格式化的字符串
	 * @param length
	 *            格式化后的长度，如果负数则返回空字符串
	 * @param infilling
	 *            如果长度不够，则填充字符
	 * @return
	 */
	public static String format(String formatted, int length, char infilling) {
		final int size = NumberUtils.max(new int[] { 0, length });
		if (StringUtils.length(formatted) > size) {
			return formatted.substring(formatted.length() - size, formatted.length());
		}
		final StringBuilder builder = new StringBuilder(size);
		while (builder.length() < size) {
			builder.append(infilling);
		}
		builder.replace(size - StringUtils.length(formatted), size, StringUtils.trimToEmpty(formatted));
		return builder.toString();
	}

	public static String getRandomNumber() {
		return getRandomStringFrom(Constants.NUM_CHARACTERS, 3);
	}

	public static String getRandomStringFrom(final int radix) {
		return getRandomStringFrom(Constants.WORD_CHARACTERS, radix);
	}

	public static String getRandomStringFrom(final String text, final int radix) {
		final int size = NumberUtils.max(new int[] { 0, radix });
		final StringBuilder builder = new StringBuilder(size);
		if (StringUtils.isNotBlank(text)) {
			for (int i = 0; i < size; i++) {
				builder.append(text.charAt(RANDOM.nextInt(text.length())));
			}
		}
		return builder.toString();
	}

	public static String toString(String wordCharacters, long value, int radix) {
		long mod = value % radix; // 取模
		long div = value / radix; // 取整
		String text = String.valueOf(wordCharacters.charAt((int) mod));
		if (div != 0) {
			if (div < radix) {
				text = wordCharacters.charAt((int) div) + text;
			} else {
				text = toString(wordCharacters, div, radix) + text;
			}
		}
		return text;
	}
}
